package net.tv90.volunteerserveradmin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import net.tv90.volunteerserveradmin.annotation.OptLogger;
import net.tv90.volunteerserveradmin.constant.OptLoggerConstant;
import net.tv90.volunteerserveradmin.constant.RoleConstant;
import net.tv90.volunteerserveradmin.exception.ServiceException;
import net.tv90.volunteerserveradmin.model.dto.TeacherDTO;
import net.tv90.volunteerserveradmin.model.dto.TeacherQueryDTO;
import net.tv90.volunteerserveradmin.model.vo.StudentVO;
import net.tv90.volunteerserveradmin.utils.entity.PageResult;
import net.tv90.volunteerserveradmin.model.vo.TeacherVO;
import net.tv90.volunteerserveradmin.service.TeacherService;
import net.tv90.volunteerserveradmin.utils.CsvUtils;
import net.tv90.volunteerserveradmin.utils.entity.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;

@Validated
@CrossOrigin
@RestController
@RequestMapping("teacher")
@Tag(name = "教师管理接口")
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    @GetMapping("/{id}")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.QUERY)
    @Operation(summary = "获取教师信息", description = "根据教师ID获取教师详细信息")
    public Result<TeacherVO> getTeacherById(@PathVariable Long id) {
        return Result.success(teacherService.getTeacherById(id));
    }

    @GetMapping("/self/{id}")
    @SaCheckRole(RoleConstant.TEACHER)
    @OptLogger(OptLoggerConstant.QUERY)
    @Operation(summary = "教师获取自己的信息", description = "教师根据自己的ID获取学生详细信息")
    public Result<TeacherVO> getTeacherSelfById(@PathVariable Long id) {
        return Result.success(teacherService.getTeacherSelfById(id));
    }

    @GetMapping("/all")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.QUERY)
    @Operation(summary = "获取所有教师", description = "获取所有教师的简要信息")
    public Result<List<TeacherVO>> getAllTeachers() {
        return Result.success(teacherService.getAllTeachers());
    }

    @PostMapping("/add")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.ADD)
    @Operation(summary = "添加教师", description = "添加新的教师信息")
    public Result<Void> addTeacher(@RequestBody TeacherDTO teacherDTO) {
        teacherService.addTeacher(teacherDTO);
        return Result.success();
    }

    @PutMapping("/update/{id}")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.UPDATE)
    @Operation(summary = "更新教师信息", description = "根据教师ID更新教师信息")
    public Result<Void> updateTeacher(@PathVariable Long id, @RequestBody TeacherDTO teacherDTO) {
        teacherService.updateTeacher(id, teacherDTO);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.DELETE)
    @Operation(summary = "删除教师", description = "根据教师ID删除教师")
    public Result<Void> deleteTeacher(@PathVariable Long id) {
        teacherService.deleteTeacher(id);
        return Result.success();
    }

    @PostMapping("/query")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.QUERY)
    @Operation(summary = "查询教师信息", description = "复杂查询获取教师详细信息")
    public Result<PageResult<TeacherVO>> queryTeacher(@RequestBody TeacherQueryDTO dto) {
        return Result.success(teacherService.queryTeacher(dto));
    }

    @GetMapping("/export")
    //@AccessLimit(seconds = 5, maxCount = 1)
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.QUERY)
    @Operation(summary = "导出教师信息", description = "导出所有教师信息为CSV文件")
    public void exportTeachersToCSV(HttpServletResponse response) throws IOException {
        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=teachers.csv");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<TeacherVO> teachers = teacherService.getAllTeachers();
        PrintWriter writer = response.getWriter();
        writer.write('\uFEFF');
        writer.println("工号,姓名,性别,院系,职位,身份证号,出生日期,地址,用户名,邮箱");
        for (TeacherVO teacher : teachers) {
            String staffNumber = CsvUtils.escapeCsvField(teacher.getStaffNumber());
            String name = CsvUtils.escapeCsvField(teacher.getName());
            String gender = CsvUtils.escapeCsvField(teacher.getGender());
            String department = CsvUtils.escapeCsvField(teacher.getDepartment());
            String position = CsvUtils.escapeCsvField(teacher.getPosition());
            String idCardNumber = CsvUtils.escapeCsvField(teacher.getIdCardNumber());
            String dateOfBirth = CsvUtils.escapeCsvField(sdf.format(teacher.getDateOfBirth()));
            String address = CsvUtils.escapeCsvField(teacher.getAddress());
            String userName = CsvUtils.escapeCsvField(teacher.getUserName());
            String email = CsvUtils.escapeCsvField(teacher.getEmail());
            StringBuilder sb = new StringBuilder();
            sb.append(staffNumber).append(",");
            sb.append(name).append(",");
            sb.append(gender).append(",");
            sb.append(department).append(",");
            sb.append(position).append(",");
            sb.append(idCardNumber).append(",");
            sb.append(dateOfBirth).append(",");
            sb.append(address).append(",");
            sb.append(userName).append(",");
            sb.append(email);
            writer.println(sb);
        }
        writer.flush();
    }

    @PostMapping("/import")
    @SaCheckRole(RoleConstant.ADMIN)
    @OptLogger(OptLoggerConstant.ADD)
    @Operation(summary = "批量导入教师信息", description = "从CSV文件批量导入教师信息")
    public Result<Void> importTeachersFromCSV(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failed("文件不能为空");
        }
        try (InputStream inputStream = file.getInputStream()) {
            CsvMapper csvMapper = new CsvMapper();
            CsvSchema schema = CsvSchema.builder()
                    .addColumn("staffNumber")
                    .addColumn("name")
                    .addColumn("gender")
                    .addColumn("department")
                    .addColumn("position")
                    .addColumn("idCardNumber")
                    .addColumn("dateOfBirth")
                    .addColumn("address")
                    .setUseHeader(true) // 表示第一行是表头
                    .build();
            MappingIterator<TeacherDTO> iterator = csvMapper
                    .readerFor(TeacherDTO.class)
                    .with(schema)
                    .readValues(inputStream);
            List<TeacherDTO> teacherDTOList = iterator.readAll();
            teacherService.batchAddTeachers(teacherDTOList);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        return Result.success();
    }


}
